package controller;

import pojo.Book;
import service.BookService;
import service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateBookServlet")
public class UpdateBookServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取表单数据
        String idStr = request.getParameter("id");
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String category = request.getParameter("category");
        String coverUrl = request.getParameter("coverUrl");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        // 创建书籍对象
        Book book = new Book();
        book.setId(Integer.parseInt(idStr));
        book.setName(name);
        book.setAuthor(author);
        book.setCategory(category);
        book.setCoverUrl(coverUrl);
        book.setDescription(description);
        book.setStatus(status != null ? status : "在库");

        // 更新书籍
        if (bookService.updateBook(book)) {
            // 更新成功
            request.getSession().setAttribute("updateSuccess", "true");
            response.sendRedirect(request.getContextPath() + "/bookList");
        } else {
            // 更新失败
            request.setAttribute("errorMsg", "更新书籍失败");
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.sendRedirect(request.getContextPath() + "/bookList");
    }
}